package com.etongwl.socketlibrary.SocketManagerCore;



/**
 * Created by jason on 16/6/27.
 *
 */
public class HanderCore {
    //消息队列
     MessageQueueCore<MessageCore> mQueue;
    //循环
     LooperCore mLooper;

    public HanderCore(){
        mLooper =LooperCore.getLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
    }

    public final MessageCore obtainMessage()
    {
        return MessageCore.obtain(this);
    }


    public void dispatchMessage(MessageCore msg) {
        handleMessage(msg);
    }
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(MessageCore msg) {//
        if (msg.what==-1){//退出
            quit();
        }
    }

    /**
     * 添加消息到消息队列
     * @param msg
     */
    public void sendMessage(MessageCore msg){
        try {
            mQueue.setMessage(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出
     */
    private void quit(){
        if (mLooper!=null){
            mLooper.quit();
        }
    }
}
